//
//  PublishTongZhiViewController.m
//  Cunli
//
//  Created by 湛亚 on 15/7/28.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "PublishTongZhiViewController.h"
#import "MyDataService.h"
#import "NSString+MD5.h"
#import "Config.h"
#import "UIColor+Addition.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

@interface PublishTongZhiViewController ()<UIScrollViewDelegate,UITextViewDelegate,UITextFieldDelegate>{
    
    UIScrollView *writeScrollView;
    UITextField *titleField,*objectField,*danWeiField,*timeField;
    UILabel *chooseTimeLabel,*placeHolderLabel;
    UITextView *contentView;
    NSMutableArray *imgDataArray;
    NSArray *picArray;
    NSString *picsUrlString,*urlString,*type;
    UIImageView *tongZhiImg,*tongGaoImg;
    UIDatePicker *datePick;
    UIButton *queDingBtn;
    int height,keyHeight,keyPosition,textFieldPosion;
    UIView *bgView;
    NSString *titleString,*saveTitle,*areaString;
}

@end

@implementation PublishTongZhiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title=@"通知通告发布";
    self.view.backgroundColor=[UIColor convertHexColorToUIColor:0xf6f6f6];
    type=@"1";
    
    [self createWriteScrollView];
    [self addViewToScrollView];
    [self addTapRecoginzer];
    [self addNavButton];
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

-(void)createWriteScrollView{
    
    writeScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight)];
    writeScrollView.contentSize= CGSizeMake(kScreenWidth, kScreenHeight);
    writeScrollView.delegate=self;
    [self.view addSubview:writeScrollView];
    
    datePick=[[UIDatePicker alloc]initWithFrame:CGRectMake(0, kScreenHeight-220, kScreenWidth, 220)];
    datePick.backgroundColor=[UIColor whiteColor];
    datePick.datePickerMode=UIDatePickerModeDateAndTime;
    datePick.date=[NSDate date];
    [datePick addTarget:self action:@selector(choose:) forControlEvents:UIControlEventValueChanged];
}

-(void)addNavButton{
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 65, 30);
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(publishThings) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIBarButtonItem *flexSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    flexSpacer.width = flexSpacer.width - 20;
    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:flexSpacer, rightBarItem, nil]];
}

-(void)publishThings{
    
    if ([titleField.text isEqualToString:@""]||[contentView.text isEqualToString:@""]) {
        [self showAlertWithMessage:@"标题或内容不能为空!"];
    }else{
        
        NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc]init];
        [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
        [CheckParams setObject:titleField.text forKey:@"title"];
        [CheckParams setObject:contentView.text forKey:@"content"];
        [CheckParams setObject:type forKey:@"type"];
        if ([objectField.text isEqualToString:@""]) {
            [CheckParams setObject:objectField.placeholder forKey:@"object"];
        }else{
            [CheckParams setObject:objectField.text forKey:@"object"];
        }
        
        if ([danWeiField.text isEqualToString:@""]) {
            [CheckParams setObject:danWeiField.placeholder forKey:@"publish"];
        }else{
            [CheckParams setObject:danWeiField.text forKey:@"publish"];
        }
        
        if ([timeField.text isEqualToString:@""]) {
            [CheckParams setObject:timeField.placeholder forKey:@"time"];
        }else{
            [CheckParams setObject:timeField.text forKey:@"time"];
        }
        
        NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
        [CheckParams setObject:resultSign forKey:@"sign"];
        [MyDataService requestURL:@"op_noticpublish.php" httpMethod:@"POST" params:CheckParams fileDatas:nil complection:^(id result) {
            
            NSLog(@"%@",result);
            NSString *str=[[result objectForKey:@"error"] objectForKey:@"text"];
            if (str) {
                
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
                hud.labelText = @"发送失败!";
                [hud hide:YES afterDelay:1];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                
                MBProgressHUD *hud = [Config createHUD];
                hud.mode = MBProgressHUDModeCustomView;
                hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
                hud.labelText = @"发送成功!";
                [hud hide:YES afterDelay:1];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }failureAction:^{
            
        }];
    }
}

- (void)showAlertWithMessage:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)goBack{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addTapRecoginzer
{
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignTheKeyboard)];
    [self.view addGestureRecognizer:tap];
}

//收起键盘
- (void)resignTheKeyboard
{
    [self.view endEditing:YES];
    writeScrollView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
}

-(void)addViewToScrollView{
    
    titleField=[[UITextField alloc]initWithFrame:CGRectMake(15, 10, kScreenWidth-30, 30)];
    titleField.delegate=self;
    titleField.layer.borderColor = [UIColor convertHexColorToUIColor:0xcecece].CGColor;
    titleField.layer.borderWidth =1.0;
    titleField.layer.cornerRadius =2.0;
    titleField.placeholder=@" 标题";
    titleField.backgroundColor=[UIColor whiteColor];
    [writeScrollView addSubview:titleField];
    
    contentView=[[UITextView alloc]initWithFrame:CGRectMake(15, 50, kScreenWidth-30, 130)];
    contentView.font=[UIFont systemFontOfSize:17];
    contentView.delegate=self;
    contentView.backgroundColor=[UIColor whiteColor];
    contentView.layer.borderColor = [UIColor convertHexColorToUIColor:0xcecece].CGColor;
    contentView.layer.borderWidth =1.0;
    contentView.backgroundColor=[UIColor whiteColor];
    contentView.layer.cornerRadius = 2.0;
    [writeScrollView addSubview:contentView];
    
    //TextView占位符
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    placeHolderLabel = [[UILabel alloc] initWithFrame:CGRectMake(3, 8, 40, 20)];
    placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
    placeHolderLabel.textColor = [UIColor convertHexColorToUIColor:0xbcbcc3];
    placeHolderLabel.backgroundColor = [UIColor clearColor];
    placeHolderLabel.alpha = 1;
    placeHolderLabel.text = @"内容";
    placeHolderLabel.font=[UIFont systemFontOfSize:18];
    [contentView addSubview:placeHolderLabel];
    
    UILabel *objectLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 190, 80, 30)];
    objectLabel.text=@"发布对象";
    objectLabel.textAlignment=0;
    [writeScrollView addSubview:objectLabel];
    objectField=[[UITextField alloc]initWithFrame:CGRectMake(100, 190, kScreenWidth-115, 30)];
    objectField.placeholder=@"全体村民";
    objectField.delegate=self;
    objectField.tag=1;
    objectField.layer.borderColor = [UIColor convertHexColorToUIColor:0xcecece].CGColor;
    objectField.layer.borderWidth =1.0;
    objectField.backgroundColor=[UIColor whiteColor];
    objectField.layer.cornerRadius = 2.0;
    [writeScrollView addSubview:objectField];
    
    UILabel *typeLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 230, 80, 30)];
    typeLabel.text=@"类       型";
    typeLabel.textAlignment=0;
    [writeScrollView addSubview:typeLabel];
    tongZhiImg=[[UIImageView alloc]initWithFrame:CGRectMake(110, 236, 16, 16)];
    tongZhiImg.image=[UIImage imageNamed:@"选中.png"];
    [writeScrollView addSubview:tongZhiImg];
    tongGaoImg=[[UIImageView alloc]initWithFrame:CGRectMake(180, 236, 16, 16)];
    tongGaoImg.image=[UIImage imageNamed:@"未选中.png"];
    [writeScrollView addSubview:tongGaoImg];
    
    UILabel *tongZhiLabel=[[UILabel alloc]initWithFrame:CGRectMake(132, 230, 40, 30)];
    tongZhiLabel.text=@"通知";
    tongZhiLabel.textAlignment=0;
    [writeScrollView addSubview:tongZhiLabel];
    
    UILabel *tongGaoLabel=[[UILabel alloc]initWithFrame:CGRectMake(202, 230, 40, 30)];
    tongGaoLabel.text=@"通告";
    tongGaoLabel.textAlignment=0;
    [writeScrollView addSubview:tongGaoLabel];
    
    UIButton *tongZhiBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    tongZhiBtn.frame = CGRectMake(105, 230, 70, 30);
    [tongZhiBtn addTarget:self action:@selector(tongZhiSecelt) forControlEvents:UIControlEventTouchUpInside];
    [writeScrollView addSubview:tongZhiBtn];
    UIButton *tongGaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    tongGaoBtn.frame = CGRectMake(180, 230, 70, 30);
    [tongGaoBtn addTarget:self action:@selector(tongGaoSecelt) forControlEvents:UIControlEventTouchUpInside];
    [writeScrollView addSubview:tongGaoBtn];
    
    UILabel *danWeiLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 270, 80, 30)];
    danWeiLabel.text=@"发布单位";
    danWeiLabel.textAlignment=0;
    [writeScrollView addSubview:danWeiLabel];
    danWeiField=[[UITextField alloc]initWithFrame:CGRectMake(100, 270, kScreenWidth-115, 30)];
    danWeiField.placeholder=[NSString stringWithFormat:@"%@村委",[Config getVillageName]];
    danWeiField.delegate=self;
    danWeiField.tag=2;
    danWeiField.layer.borderColor = [UIColor convertHexColorToUIColor:0xcecece].CGColor;
    danWeiField.layer.borderWidth =1.0;
    danWeiField.backgroundColor=[UIColor whiteColor];
    danWeiField.layer.cornerRadius = 2.0;
    [writeScrollView addSubview:danWeiField];
    
    UILabel *timeLabel=[[UILabel alloc]initWithFrame:CGRectMake(15, 310, 80, 30)];
    timeLabel.text=@"发布时间";
    timeLabel.textAlignment=0;
    [writeScrollView addSubview:timeLabel];
    
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    
    timeField=[[UITextField alloc]initWithFrame:CGRectMake(100, 310, kScreenWidth-115, 30)];
    timeField.placeholder=locationString;
    timeField.delegate=self;
    timeField.tag=2;
    timeField.layer.borderColor = [UIColor convertHexColorToUIColor:0xcecece].CGColor;
    timeField.layer.borderWidth =1.0;
    timeField.backgroundColor=[UIColor whiteColor];
    timeField.layer.cornerRadius = 2.0;
    timeField.inputView=datePick;
    [writeScrollView addSubview:timeField];
}

-(void)choose:(UIDatePicker *)pick{
    
    NSDateFormatter *format=[[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm"];
    timeField.text=[format stringFromDate:pick.date];
}

-(void)tongZhiSecelt{
    
    type=@"1";
    tongZhiImg.image=[UIImage imageNamed:@"选中.png"];
    tongGaoImg.image=[UIImage imageNamed:@"未选中.png"];
}

-(void)tongGaoSecelt{
    
    type=@"2";
    tongZhiImg.image=[UIImage imageNamed:@"未选中.png"];
    tongGaoImg.image=[UIImage imageNamed:@"选中.png"];
}

//将要开始编辑
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if (kScreenHeight==480) {
        
        writeScrollView.frame = CGRectMake(0, -45, kScreenWidth, kScreenHeight);
    }
    return YES;
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    textFieldPosion=textField.frame.origin.y+50;
    [self performSelector:@selector(delayMethod) withObject:nil afterDelay:0.5f];
}

-(void)delayMethod{
    
    //NSLog(@"uitextfield： %d",textFieldPosion);
    //NSLog(@"uitextfield： %d",keyPosition);
    if (textFieldPosion>keyPosition) {
        writeScrollView.frame = CGRectMake(0, (keyPosition-textFieldPosion-100), kScreenWidth, kScreenHeight);
    }
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    //键盘位置
    keyPosition = keyboardRect.origin.y;
    //键盘高度
    //keyHeight=keyboardRect.size.height;
    //bgView.frame=CGRectMake(0,keyPosition-40-64, screenWidth, 40);
    //NSLog(@"键盘位置%f",keyboardRect.origin.y);
}

//输入框要编辑的时候
- (void)textChanged:(NSNotification *)notification
{
    if ([[contentView text] length] == 0) {
        placeHolderLabel.alpha=1;
    }
    else {
        placeHolderLabel.alpha=0;
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextViewTextDidChangeNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
